import 'package:flutter/material.dart';
import 'package:ribo_base_core/base_models/base_chart_axis.dart';
import 'package:ribo_base_core/base_models/base_chart_stack_bars_lines_model.dart';
import 'package:ribo_base_core/base_models/base_chart_model.dart';
import 'package:ribo_base_core/base_styles/base_chart_style.dart';
import 'base_chart.dart';

class BaseChartStackBarsLines extends StatefulWidget {
  BaseChartStackBarsLines({Key key, @required this.model, this.itemPress, this.extraScript}) : super(key: key);
  final BaseChartStackBarsLinesModel model;
  final Function(String) itemPress;
  final String extraScript;


  @override
  _BaseChartStackBarsLinesState createState() =>
      _BaseChartStackBarsLinesState();
}

class _BaseChartStackBarsLinesState extends State<BaseChartStackBarsLines> {
  Map<String, dynamic> _option;

  @override
  Widget build(BuildContext context) {
    _handleModel();

    return BaseChart(
        model:
            BaseChartModel(style: widget.model?.style, itemPress: (str) {widget.itemPress(str);}, extraScript: widget.extraScript, option: this._option));
  }

  void _handleModel() {
    List<BaseChartStackBarsLinesSeries> series = widget.model.series;
    List<String> legends = series.map((item) => item.name).toList();
    List<String> xAxisData = [];
    series.forEach((element) {
      List list = element.data;
      list.forEach((data) {
        xAxisData.add(data.name);
      });
    });

    // xAxisData去重
    var set = new Set<String>();
    set.addAll(xAxisData);
    xAxisData = set.toList();

    List<String> xAxisDataFormat = [];
    xAxisData.forEach((element) {
      xAxisDataFormat.add(element.substring(element.lastIndexOf('-')+1));
    });

    BaseChartAxis baseChartAxis = BaseChartAxis();
    this._option = {
      'legend': {
        ...BaseChartLegendStyle().toJson(),
        ...widget.model?.style?.legend?.toJson() ?? {},
        'data': legends,
      },
      "xAxis": [
        {
          ...(widget.model?.axis ?? baseChartAxis).toJson()['xAxis'],
          "type": 'category',
        }
      ],
      "yAxis": [
        {
          "type": 'value',
          "position": "left",
          ...(widget.model?.axis ?? baseChartAxis).toJson()['yAxis'],
        },
        {
          "type": 'value',
          "position": "right",
          ...(widget.model?.axis ?? baseChartAxis).toJson()['yAxis'],
        }
      ],
      'tooltip': {
        'trigger': 'axis',
        "triggerOn": "click",
        "confine": true,
        'axisPointer': {'type': 'shadow'},
        'formatter': widget.model?.tooltipFormatter?.toJson()
      },
      "dataZoom": widget.model.dataZoom,
      'series': [
        ...series
            .map((item) => {
                  'name': item.name,
                  // "barWidth": '65%',
                  'type': item.isLine ? 'line' : 'bar',
                  if(item.isLine) "smooth": true,
                  'stack': item.isLine ? '' : item.stackName,
                  'data': item.data.map((e) => e.toJson()).toList(),
                  'itemStyle': {'color': item.isGradient ? item.gradientColor : item.color},
                  "xAxisIndex": widget.model.isHorizontal == true
                      ? (item.isLine == true
                          ? widget.model.lineAxisIndex
                          : widget.model.barAxisIndex)
                      : 0,
                  "yAxisIndex": widget.model.isHorizontal != true
                      ? (item.isLine == true
                          ? widget.model.lineAxisIndex
                          : widget.model.barAxisIndex)
                      : 0,
                  'label': {
                    "show": true,
                    "fontSize": 8,
                    "color": "#333",
                    "formatter": widget.model?.labelFormatter
                  }
                })
            .toList(),
        ...(widget.model?.markLinke == null
            ? []
            : [
                {'type': 'bar', 'name': '', 'markLine': widget.model?.markLinke}
              ])
      ],
    };

    if (widget.model?.isHorizontal == true) {
      this._option['yAxis'] = [
        {
          ...(widget.model?.axis ?? baseChartAxis).toJson()['yAxis'],
          "type": 'category',
          "data": xAxisDataFormat
        }
      ];
      this._option["xAxis"] = [
        {
          ...(widget.model?.axis ?? baseChartAxis).toJson()['xAxis'],
          "type": 'value',
          "position": "top",
        },
        {
          ...(widget.model?.axis ?? baseChartAxis).toJson()['xAxis'],
          "type": 'value',
          "position": "bottom",
        }
      ];

      if (widget.model?.barAxisMin != null)
        this._option['xAxis'][widget.model.barAxisIndex]['min'] =
            widget.model?.barAxisMin;
      if (widget.model?.barAxisMax != null)
        this._option['xAxis'][widget.model.barAxisIndex]['max'] =
            widget.model?.barAxisMax;
      if (widget.model?.lineAxisMin != null)
        this._option['xAxis'][widget.model.lineAxisIndex]['min'] =
            widget.model?.lineAxisMin;
      if (widget.model?.lineAxisMax != null)
        this._option['xAxis'][widget.model.lineAxisIndex]['max'] =
            widget.model?.lineAxisMax;

      if( widget.model.axisLabelFormatter != null) {
        this._option['xAxis'][widget.model.barAxisIndex]['axisLabel'] =
            this._option['xAxis'][widget.model.barAxisIndex]['axisLabel'] ??
                <Map<String, dynamic>>{};
        this._option['xAxis'][widget.model.barAxisIndex]['axisLabel']
        ['formatter'] = widget.model.axisLabelFormatter?.toJson();
      }

      if( widget.model.lineAxisLabelFormatter != null) {
        this._option['xAxis'][widget.model.lineAxisIndex]['axisLabel'] =
            this._option['xAxis'][widget.model.lineAxisIndex]['axisLabel'] ??
                <Map<String, dynamic>>{};
        this._option['xAxis'][widget.model.lineAxisIndex]['axisLabel']
        ['formatter'] = widget.model.lineAxisLabelFormatter?.toJson();
      }
    } else {
      this._option['xAxis'] = [
        {
          ...(widget.model?.axis ?? baseChartAxis).toJson()['xAxis'],
          "type": 'category',
          "data": xAxisDataFormat
        }
      ];
      this._option["yAxis"] = [
        {
          "type": 'value',
          "position": "left",
          ...(widget.model?.axis ?? baseChartAxis).toJson()['yAxis'],
        },
        {
          "type": 'value',
          "position": "right",
          ...(widget.model?.axis ?? baseChartAxis).toJson()['yAxis'],
        }
      ];

      if (widget.model?.barAxisMin != null)
        this._option['yAxis'][widget.model.barAxisIndex]['min'] =
            widget.model?.barAxisMin;
      if (widget.model?.barAxisMax != null)
        this._option['yAxis'][widget.model.barAxisIndex]['max'] =
            widget.model?.barAxisMax;
      if (widget.model?.lineAxisMin != null)
        this._option['yAxis'][widget.model.lineAxisIndex]['min'] =
            widget.model?.lineAxisMin;
      if (widget.model?.lineAxisMax != null)
        this._option['yAxis'][widget.model.lineAxisIndex]['max'] =
            widget.model?.lineAxisMax;

      if( widget.model.axisLabelFormatter != null){
        this._option['yAxis'][widget.model.barAxisIndex]['axisLabel'] =
            this._option['yAxis'][widget.model.barAxisIndex]['axisLabel'] ??
                <Map<String, dynamic>>{};
        this._option['yAxis'][widget.model.barAxisIndex]['axisLabel']
        ['formatter'] = widget.model.axisLabelFormatter?.toJson();
      }

      if( widget.model.lineAxisLabelFormatter != null){
        this._option['yAxis'][widget.model.lineAxisIndex]['axisLabel'] =
            this._option['yAxis'][widget.model.lineAxisIndex]['axisLabel'] ??
                <Map<String, dynamic>>{};

        this._option['yAxis'][widget.model.lineAxisIndex]['axisLabel']
        ['formatter'] = widget.model.lineAxisLabelFormatter?.toJson();
      }
    }
  }
}
